import {Component, OnDestroy, OnInit} from '@angular/core';
import {MsgConstants} from '../../../constants/constants';
import {TableUtil} from '../../../util/table-util';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {ActivatedRoute, Router} from '@angular/router';
import {Path} from '../../../portal/admin/admin-breadcrumb/breadcrumb';
import {MsgResult} from '../../../models/msg-result';
import {Observable} from 'rxjs/Observable';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {DaAPI, DaChartColor, DaChartTitle, DaFactorColor, DaFactorName} from '../da-constants';
import {DaSoaService} from './da-soa.service';

declare var $;
declare var moment;
declare var echarts;

@Component({
  selector: 'app-da-soa',
  templateUrl: './da-soa.component.html',
  styleUrls: ['./da-soa.component.css']
})
export class DaSoaComponent implements OnInit, OnDestroy {
  config;
  pointType = 'skyEyeSite'; // 点位类型
  factor = 'PM2_5';
  timeDataType = 'hourData';
  timeDataFormat = 'YYYY-MM-DD HH:00:00';
  siteCode = '';
  rangeCode = '';
  siteArr: Array<any> = [];
  nationCode = '';
  barObj: any;
  chartOption: object;
  colorArr: Array<any> = [];
  isLoading = true;
  resizeEnent: any;
  timeDataArr: Array<any> = [];
  table: any;
  startDate = new Date(moment().subtract(1, 'M').format('YYYY/MM/DD HH:00'));
  endDate =  new Date();
  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  componentArr: Array<any> = [];
  checkObjArr: Array<any> = [];
  checkComArr: Array<any> = [];
  compareCom = '';
  typePieObj: any;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: OneDialogService,
    private response: ResponseUtil,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private soaService: DaSoaService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.screenChange();
    this.initData();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.destroyResize();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    const path = new Path('活性水平', '');
    this.pageSubject.pushPage('SOA生成潜势', '查询', path);
  }

  initData = () => {
    // $(window.innerHeight)[0] - 230
    $('#soaCom').css({'height': 500 + 'px'});
    $('#soaPieCom').css({'height': 550 + 'px'});
    this.timeDataArr = [
      {'name': '小时', dataType: 'hourData', formatter: 'YYYY-MM-DD HH:00', mode: 'day', format: 'YYYY-MM-DD HH:00:00'},
      {'name': '日', dataType: 'dayData', formatter: 'YYYY-MM-DD', mode: 'day', format: 'YYYY-MM-DD 00:00:00'},
      {'name': '月', dataType: 'monthData', formatter: 'YYYY-MM', mode: 'month', format: 'YYYY-MM-01 00:00:00'},
      {'name': '年', dataType: 'yearData', formatter: 'YYYY', mode: 'month', format: 'YYYY-01-01 00:00:00'}
    ];
    this.barObj = echarts.init(document.getElementById('soaCom'));
    this.typePieObj = echarts.init(document.getElementById('soaPieCom'));
    this.colorArr = [
      '#1890FF', '#2FC25B', '#FACC14', '#8543E0', '#13C2C2', '#3436c7',
      '#531DAB', '#2F54EB', '#40A9FF', '#5CDBD3', '#B7EB8F', '#FFE58F',
      '#FFC069', '#FF7A45'];
    const vocsData  = {
      title: DaChartTitle.daSoaTitle,
      factor: ['苯', '甲苯', '间/对二甲苯', '邻二甲苯', '苯乙烯', '1,2,3-三甲基苯', '1,2,4-三甲基苯', '1,3,5-三甲基苯', '甲基环乙烷', '环乙烷'],
      factorData: [2.007, 1.226, 0.560, 0.490, 0.387, 0.231, 0.203, 0.187, 0.058, 0.035]
    };
    // this.barRender(vocsData);
  };
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEnent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        // 这里处理页面变化时的操作
        this.barObj.resize();
        this.typePieObj.resize();
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEnent.unsubscribe();
  }
  search() {
    const startDate = new Date(moment(this.startDate).format(this.timeDataFormat));
    const endDate = new Date(moment(this.endDate).format(this.timeDataFormat));
    if (startDate > endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.isLoading = true;
      this.getSOAData();
      this.getClassifieRatioData();
    }
  }

  /**
   * 下拉框
   */
  typeChange = (isOpen) => {
    if (!isOpen) {
      this.search();
    }
  };
  /**
   * 柱状图
   * @param data
   */
  private barRender = (data) => {
    const compareChart = this.barObj;
    const nameArr = [];
    data.nameList.forEach(val => nameArr.push(DaFactorName[val] || val));
    // 图表配置信息
    const option = {
      title : {
        text: DaChartTitle.daSoaTitle,
        left: 'center'
      },
      tooltip : {
        trigger: 'item',
        formatter: '{b} : {c}'
      },
      grid: [{
        top: 40
      }],
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      color: this.colorArr,
      xAxis : [
        {
          name: '浓度 μg/m³',
          type : 'value'
        }
      ],
      yAxis : [
        {
          type : 'category',
          data : nameArr.reverse(),
          axisTick: {
            alignWithLabel: true
          }
        }
      ],
      series : [
        {
          type: 'bar',
          barMaxWidth: 40,
          label: {
            normal: {
              show: true,
              position: 'right'
            }
          },
          data: data.dataList.reverse()
        }
      ]
    };
    compareChart.setOption(option, {notMerge: true});
  };

  /**
   * 时间类型切换
   * @param timeData
   */
  timeDataChange(timeData) {
    if (this.timeDataType === timeData.dataType) {
      return false;
    }
    this.timeDataType = timeData.dataType;
    this.timeDataFormat = timeData.format;
    this.changeStartAndEndDate();
    this.search();
  }
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }
  get timeFormatter() {
    let formatter = 'YYYY-MM-DD';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        formatter = val.formatter;
      } else {
        return true;
      }
    });
    return formatter;
  }
  get timeMode() {
    let dataMode = 'day';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        dataMode = val.mode;
      } else {
        return true;
      }
    });
    return dataMode;
  }
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.soaService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.getClassData();
        this.getSOAData();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };
  /**
   * 获取vocs分类数据
   */
  getClassData = () => {
    this.soaService.getVocClassData().subscribe(
      result => this.responseUtil.success(result, this.handleClass),
      error => this.responseUtil.error(error)
    )
  };
  handleClass = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.componentArr = result.data;
        this.componentArr.unshift(
          {
            label: '总VOCs',
            value: 'all',
            children: [
              {
                label: '三大类',
                value: 'com'
              },
              {
                label: '14小类',
                value: 'small'
              }
            ]
          }
        );
        this.compareCom = this.componentArr[0].children[0].value;
        this.updateCom(this.componentArr[0].children[0], 'class');
        // this.componentArr.forEach((factorData, i) => {
        //   if (factorData.hasOwnProperty('children')) {
        //     factorData.children.forEach((factor, j) => {
        //       if (j === 0) {
        //         factorData.children[0].checked = true;
        //       }
        //       factor.label = DaFactorName[factor.value] || factor.label;
        //       if (factor.hasOwnProperty('children')) {
        //         // factor.children = [];
        //       } else {
        //         if (j === 0) {
        //           factor.checked = true;
        //         }
        //       }
        //     })
        //   } else {
        //     // factorData.checked = true;
        //   }
        // });
        // this.updateComCheck();
        // this.getClassifieData();
        this.getClassifieRatioData();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取图表数据
   */
  getSOAData() {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      rangeCode: this.rangeCode,
      startTime : this.startDate ? moment(this.startDate).format(this.timeDataFormat) : '',
      endTime : this.endTime
    };
    this.soaService.getSOAData(dataObj).subscribe(
      result => this.response.success(result, this.handleO3data),
      error => this.response.error(error)
    );
  }
  handleO3data = (result: MsgResult) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.dataList) {
        this.barRender(result.data);
      } else {
        this.barRender({
          nameList: [],
          dataList: []
        });
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取图表数据
   */
  getClassifieRatioData() {
    const dataObj = {
      siteCode: this.siteCode,
      dataType: this.timeDataType,
      factors: this.checkComArr.join('|'),
      rangeCode: this.rangeCode,
      startTime : this.startDate ? moment(this.startDate).format(this.timeDataFormat) : '',
      endTime : this.endTime
    };
    this.soaService.getSOARatioData(dataObj).subscribe(
      result => this.response.success(result, this.handleClasFiRatioData),
      error => this.response.error(error)
    );
  }
  handleClasFiRatioData = (result: MsgResult) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.pieRender(result.data);
      } else {
        this.pieRender([]);
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 饼图
   * @param data
   */
  pieRender(data) {
    const compareChart = this.typePieObj;
    data.forEach((val, i) => {
      const itemObj = {
        itemStyle: {
          color: DaFactorColor[val.code] || DaChartColor.color[i]
        }
      };
      val = Object.assign(val, itemObj);
    });
    const checkedValue = this.checkObjArr[0];
    let title = '';
    if (checkedValue.value === 'com') {
      title = '总VOCs中各大类的SOA生成潜势';
    } else if (checkedValue.value === 'small') {
      title = '总VOCs中各细分类的SOA生成潜势';
    } else {
      const name = checkedValue.type === 'class' ? '中各细分类的SOA生成潜势' : '中各物质的SOA生成潜势';
      title = checkedValue.name + name;
    }
    // 图表配置信息
    const option = {
      title : {
        text: title + DaChartTitle.daClafiedPieTitle ,
        left: 'center',
      },
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      tooltip : {
        trigger: 'item',
        formatter: '{b} \n ({c},{d}%)'
      },
      color: this.colorArr,
      series : []
    };
    if (data.length > 0) {
      option.series.push({
        type: 'pie',
        radius : '50%',
        center: ['50%', '50%'],
        data: data,
        label: {
          formatter: '{b}\n{d}%', // :{d}%
          color: '#333'
        },
        labelLine: {
          length: 10,
          length2: 10,
          lineStyle: {
            color: '#333'
          }
        },
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      })
    } else {
      option.series.push({
        type: 'pie',
        radius: ['100', '100'],
        hoverAnimation: false,
        label: {
          normal: {
            position: 'center'
          }
        },
        data: [{
          value: '1',
          name: '贡献值为0',
          tooltip: {
            show: false
          },
          itemStyle: {
            normal: {
              color: '#333',
            }
          },
          label: {
            normal: {
              // formatter: '{d} %',
              textStyle: {
                fontSize: 18,
                fontWeight: 600,
                color: '#333',
              }
            }
          }
        }]
      })
    }
    compareChart.setOption(option, {notMerge: true});
  }
  updateCom = (component, type) => {
    this.checkObjArr = [];
    this.checkComArr = [];
    this.checkObjArr.push({name: component.label, value: component.value, type: type});
    if (component.hasOwnProperty('children')) {
      component.children.forEach(val => this.checkComArr.push(val.value))
    } else {
      if (component.value === 'com') {
        this.componentArr.forEach((val, i) => {
          if (val.hasOwnProperty('children')) {
            if (i > 0) {
              this.checkComArr.push(val.value)
            }
          }
        })
      } else {
        this.componentArr.forEach((factor, i) => {
          if (factor.hasOwnProperty('children')) {
            if (i > 0) {
              factor.children.forEach(val => this.checkComArr.push(val.value));
            }
          }
        })
      }
    }
  };
  get endTime () {
    let endDate = '';
    const daysInMonth = moment(this.endDate, "YYYY-MM").daysInMonth();
    if (this.endDate) {
      if (this.timeDataType === 'yearData') {
        endDate = moment(this.endDate).format('YYYY-12-31 23:59:59')
      } else if (this.timeDataType === 'monthData') {
        endDate = moment(this.endDate).format('YYYY-MM-' + daysInMonth +' 23:59:59')
      } else if (this.timeDataType === 'dayData') {
        endDate = moment(this.endDate).format('YYYY-MM-DD 23:59:59')
      } else {
        endDate = moment(this.endDate).format('YYYY-MM-DD HH:59:59')
      }
    }
    return endDate;
  }
}
